package edu.nf.api.controller.user;

import edu.nf.api.controller.BaseController;
import edu.nf.api.fileutil.FileUploadUtil;
import edu.nf.util.JwtUtil;
import edu.nf.waimai.model.user.User;
import edu.nf.waimai.service.user.impl.UserServiceImpl;
import org.nf.web.annotation.RequestMapping;
import org.nf.web.annotation.RequestParam;
import org.nf.web.servlet.View;
import org.nf.web.servlet.view.JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.util.HashMap;


/**
 * @Date 2023-06-20
 * @Author qiu
 * 用户登录控制器
 */
public class LoginController extends BaseController {

    /**
     * 用户登录 --- 账号密码
     *
     * @param userName 账号
     * @param pwd      密码
     * @param session
     * @return
     */
    @RequestMapping("/login")
    public View userLogin(@RequestParam("userName") String userName, @RequestParam("pwd") String pwd, HttpSession session) {

        User login = new UserServiceImpl().login(userName, pwd);

        // 转发试图
        //ForwardView forwardView = new ForwardView("index.html");

        // 获取登录信息，存储到 token 中
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", login.getUname());

        // 创建 token
        String token = JwtUtil.createToken(map, 5 * 60 * 8000);

        // 将 token 保存到作用域中
        //session.setAttribute("token",token);

        return new JsonView(success(token));
    }

    /**
     * 用户登录 -- 手机号码 + 短信验证
     *
     * @param phone
     * @param key
     * @return
     */
    @RequestMapping("/user/userPhoneLogin")
    public View userPhoneLogin(@RequestParam("userPhone") String phone, @RequestParam("key") String key) {
        User user = new UserServiceImpl().userLoginPhone(phone, key);

        // 获取登录信息，存储到 token 中
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", user.getUname());

        // 创建 token
        String token = JwtUtil.createToken(map, 1 * 24 * 60 * 60 * 1000);

        return new JsonView(success(token));
    }

    @RequestMapping("/user/uploadImg")
    public View userUploadImg(Part[] file, HttpServletRequest request, HttpServletResponse response){
        String filename = "";
        for (Part part1 : file) {
            //获取路径
            String filePath = request.getServletContext().getRealPath("/images/user");
            //创建工具类
            FileUploadUtil fileUploadUtil = new FileUploadUtil();
            //设置文件大小
            fileUploadUtil.setMaxSize(1 * 1024 * 1024);
            //设置文件的后缀
            fileUploadUtil.setAllowFileExt("jpg,png,jpeg");
            //文件名称
            filename = fileUploadUtil.upload(part1, filePath);
        }
        return new JsonView(success(filename));
    }
}
